package org.ghost.spring.cloud.config.server.demo.common.json.deserialize;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Long[]日期数组转String[]数组
 */
public class LongArray2DateStringArrayDeserializer extends JsonDeserializer<String[]> {

    @Override
    public String[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonToken currentToken = p.getCurrentToken();
        if (currentToken == JsonToken.START_ARRAY) {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<Long> dates = Lists.newArrayList();
            while (p.nextLongValue(0L) > 0L) {
                dates.add(p.getLongValue());
            }
            String[] result = new String[dates.size()];
            for (int i = 0; i < dates.size(); i++) {
                result[i] = sim.format(new Date(dates.get(i)));
            }
            return result;
        }
        return null;
    }
}
